import { exec } from "child_process";
import { Restart } from "../../other/restart.js";

export class Update extends plugin {
    constructor() {
        super({
            name: 'FanSky_Qs插件更新',
            dsc: 'FanSky_Qs插件更新',
            event: 'message',
            priority: 1000,
            rule: [
                {
                    reg: /^#?([Ff]an((Ss)?ky)?)(强制)?更新$/,
                    fnc: 'update',
                    permission: 'master'
                }
            ]
        })
    }

    async update(e) {
        let _path = process.cwd()
        let isForce = e.msg.includes('强制')
        let command = 'git  pull'
        if (isForce) {
            command = 'git  checkout . && git  pull'
            e.reply('正在执行强制更新操作，请稍等')
        } else {
            e.reply('正在执行更新操作，请稍等')
        }
        exec(command, { cwd: `${_path}/plugins/FanSky_Qs/` }, function (error, stdout, stderr) {
            if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
                e.reply('目前已经是最新版FanSky了~')
                return true
            }
            if (error) {
                e.reply('FanSky更新失败！\nError code: ' + error.code + '\n' + error.stack + '\n 请稍后重试。')
                return true
            }
            e.reply('FanSky更新成功, 正在尝试重启Yunzai...')
            // 重启
            setTimeout(() => new Restart(e).restart(), 1000)
        })
    }
}
